<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #userList a {
            text-decoration: none;
            margin-left: 10px;
            color: black;
        }

        .active {
            background-color: black;
            color: aliceblue;
        }
    </style>
</head>

<body>
    <div id="userList">

    </div>
    <div id="chatList">

    </div>
    <div>
        <input type="text" id="msg" /><button onclick="senMsg()">发送</button>
    </div>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.3.6/axios.js"></script>
<script src="js/qs.js"></script>
<script>
    let ws = null
    let uid = null
    let userList = []
    // 这个是断开重连
    setInterval(() => {
        if (!ws) {
            ws = new WebSocket("ws://127.0.0.1:3000")
        }
        ws.onopen = function () {
            console.log("链接成功")
            // 这个是登录
            ws.send(JSON.stringify({ type: "kflogin", user: 'kf1', uid: 1 }))
            // 这个是心跳检测
            setInterval(() => {
                ws.send(JSON.stringify({ type: "heart", msg: "心跳检测" }))
            }, 1000)
        }

        ws.onmessage = function (evt) {
            console.log(evt.data)
            let data = JSON.parse(evt.data)
            console.log(data.data)
            if (data.type == "kflogin") {
                userList = data.data
                for (var i = 0; i < data.data.length; i++) {

                    $("#userList").append(`<a id="bg${data.data[i].id}" href="javascript:checkUser(${data.data[i].id})">${data.data[i].username}</a>`)


                }
            } else if (data.type == "kfmsg") {
                console.log(data)
                $("#chatList").append(`<div class="left">${data.data}</div>`)
            }
        }

        ws.onerror = function (err) {
            ws = null
        }

        ws.onclose = function () {
            ws = null
        }
    }, 1000)


    function senMsg() {
        if (uid) {
            let msg = $("#msg").val()
            ws.send(JSON.stringify({ type: "kfmsg", msg: msg, uid: uid, kfid: 1 }))
            $("#msg").val("")
            $("#chatList").append(`<div class="right">${msg}</div>`)
        } else {
            alert("请选择用户")
        }

    }

    function checkUser(id) {
        uid = id
        $("a").css("color", "#000")
        $(`a`).css("background-color", "#fff")
        $(`#bg${id}`).css("color", "#fff")
        $(`#bg${id}`).css("background-color", "#000")
        // console.log(userinfo)
    }
    // 要有一个用户列表
    // 要有未读消息提示
    // 可以回复消息
    // 转人工 才可以给客服发送消息
</script>

</html>